package com.bluesky.plum.util;

import org.apache.commons.beanutils.PropertyUtils;

import com.bluesky.plum.richdomain.annotation.OUMEntity;

public class EntityUtil {
	public static boolean isOUMEntity(Object obj) {
		try {
			OUMEntity oumEntity = obj.getClass().getAnnotation(OUMEntity.class);
			return true;
		} catch (NullPointerException e) {
			return false;
		}
	}

	public static String getIdFieldName(Object obj) {
		try {
			OUMEntity oumEntity = obj.getClass().getAnnotation(OUMEntity.class);
			return oumEntity.id();
		} catch (NullPointerException e) {
			throw new RuntimeException("it is not a OUM entity:" + obj);
		}

	}

	public static Object getIdFieldValue(Object obj) {
		String name = getIdFieldName(obj);
		try {

			Object value = PropertyUtils.getProperty(obj, name);

			return value;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e);
		}

	}

	public static boolean idEquals(Object obj1, Object obj2) {
		Object v1 = getIdFieldValue(obj1);
		Object v2 = getIdFieldValue(obj2);
		return v1.equals(v2);
	}
}
